package cn.tedu.knows.sys.controller;


import cn.tedu.knows.commons.model.User;
import cn.tedu.knows.sys.service.IUserService;
import cn.tedu.knows.sys.vo.RegisterVo;
import cn.tedu.knows.sys.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-05-25
 */
@RestController
@RequestMapping("/v1/users")
@Slf4j
public class UserController {


    @Autowired
    private IUserService userService;

    //查询获得所有讲师的控制器方法
    @GetMapping("/master")
    public List<User> master(){
        List<User> masters=userService.getTeachers();
        return masters;
    }

    @GetMapping("/me")
    public UserVo me(
            @AuthenticationPrincipal UserDetails user){
        System.out.println(user);
        UserVo userVo=userService
                .getCurrentUserVo(user.getUsername());
        return userVo;
    }
    @PostMapping("/register")
    //@Validated表示激活紧随其后的类型的SpringValidation验证
    //要验证的对象参数后面新增一个参数类型为BindingResult
    //SpringValidation会将验证结果自动赋值到这个对象中
    public String registerStudent(
            @Validated RegisterVo registerVo,
            BindingResult result) {
        //第二个参数registerVo会自动赋值到第一个参数中的{}的位置
        log.debug("获得用户填写的信息:{}", registerVo);
        //判断result对象中有没有错误
        if (result.hasErrors()) {
            //如果有错误,进入if语句处理
            //获得错误消息
            String msg = result.getFieldError()
                    .getDefaultMessage();
            return msg;
        }
        //执行注册
        userService.registerStudent(registerVo);
        return "注册成功";
    }





}
